package com.microstation.controller.system;

import com.microstation.common.Assist;
import com.microstation.common.Result;
import com.microstation.entity.po.AdminInfo;
import com.microstation.entity.po.RoleInfo;
import com.microstation.enums.ResultEnum;
import com.microstation.service.AdminInfoService;
import com.microstation.service.RoleInfoService;
import com.microstation.util.MD5;
import com.microstation.util.StringUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

/**
 * @author XuCong
 * @date 2018-02-15
 */
@RestController
@RequestMapping("/api/admin")
public class AdminController {
    private final static MD5 md5 = new MD5();
    private final static Logger logger = LoggerFactory.getLogger(LoginController.class);
    @Autowired
    private AdminInfoService adminInfoService;
    @Autowired
    private RoleInfoService roleInfoService;

    /**
     * 用户修改密码
     *
     * @param oldpassword
     * @param password
     * @return
     */
    @RequestMapping(value = "/updPsd", method = RequestMethod.POST)
    public Result updPsd(String oldpassword, String password) {
        if (StringUtil.isEmpty(oldpassword)) {
            return new Result(true, ResultEnum.EMPTY.getType(), "请输入旧密码");
        }
        if (StringUtil.isEmpty(password)) {
            return new Result(true, ResultEnum.EMPTY.getType(), "请输入新密码");
        }
        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();
        AdminInfo adminInfo = (AdminInfo) session.getAttribute("adminLogin"), oldAdminInfo = null;
        try {
            if (adminInfo == null) {
                return new Result(true, ResultEnum.NOSESSION.getType(), ResultEnum.NOSESSION.getInfo(),
                        "login.html");
            }
            oldAdminInfo = adminInfoService.findOne(adminInfo.getId());
            oldpassword = md5.getMD5ofStr(oldpassword);
            if (!oldpassword.equals(oldAdminInfo.getPassword())) {
                return new Result(true, ResultEnum.FAIL.getType(), "旧密码错误", "login.html");
            }
            password = md5.getMD5ofStr(password);
            oldAdminInfo.setPassword(password);
            AdminInfo param = new AdminInfo();
            param.setId(oldAdminInfo.getId());
            param.setPassword(oldAdminInfo.getPassword());
            adminInfoService.updateNotNullById(param);
            session.setAttribute("adminLogin", oldAdminInfo);
            return new Result(false, ResultEnum.SUCCESS.getType(), ResultEnum.SUCCESS.getInfo(), null);
        } catch (Exception e) {
            logger.info(ResultEnum.ERROR.getType(), e);
            return new Result(true, ResultEnum.ERROR.getType(), ResultEnum.ERROR.getInfo(), null);
        }
    }

    /**
     * 管理员列表
     *
     * @param key
     * @param pageIndex
     * @param limit
     * @return
     */
    @RequestMapping(value = "/listAdmin", method = RequestMethod.POST)
    public Result listAdmin(@RequestParam(name = "key", required = false) String key,
                            @RequestParam(name = "pageIndex", required = true, defaultValue = "0") Integer pageIndex,
                            @RequestParam(name = "limit", required = true, defaultValue = "10") Integer limit) {
        try {
            Assist assist = new Assist();
            if (StringUtil.isNotEmpty(key)) {
                assist.andLike("account", StringUtil.formatLike(key));
            }
            assist.setRowSize(limit);
            assist.setPage(pageIndex + 1);
            Result result = adminInfoService.find(assist);

            RoleInfo roleInfo = null;
            List<AdminInfo> list = (List<AdminInfo>) result.getRows();
            for (AdminInfo adminInfo : list) {
                roleInfo = roleInfoService.findOne(adminInfo.getRoleId());
                adminInfo.setRoleInfo(roleInfo);
            }
            return new Result(result.getResults(), result.getRows());
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(Boolean.TRUE, ResultEnum.ERROR.getInfo(), 0L);
        }
    }

    /**
     * 新增账号
     *
     * @param adminInfo
     * @return
     */
    @RequestMapping(value = "/saveAdmin", method = RequestMethod.POST)
    public Result saveAdmin(AdminInfo adminInfo) {
        try {
            if (StringUtil.isEmpty(adminInfo.getAccount())) {
                return new Result(true, ResultEnum.EMPTY.getType(), "请输入账号", null);
            }
            if (StringUtil.isEmpty(adminInfo.getPassword())) {
                return new Result(true, ResultEnum.EMPTY.getType(), "请输入密码", null);
            }
            adminInfo.setPassword(md5.getMD5ofStr(adminInfo.getPassword()));
            adminInfo.setGmtCreate(Calendar.getInstance().getTime());
            adminInfo.setGmtModified(adminInfo.getGmtCreate());
            return adminInfoService.saveAdmin(adminInfo);
        } catch (Exception e) {
            logger.info(ResultEnum.ERROR.getType(), e);
            return new Result(true, ResultEnum.ERROR.getType(), ResultEnum.ERROR.getInfo(), null);
        }
    }

    /**
     * 修改账户
     *
     * @param id
     * @param account
     * @param password
     * @return
     */
    @RequestMapping(value = "/updateAdmin", method = RequestMethod.POST)
    public Result updateAdmin(@RequestParam(name = "id", required = true) Long id,
                              @RequestParam(name = "account", required = true) String account,
                              @RequestParam(name = "password", required = true) String password,
                              @RequestParam(name = "roleId", required = true) Long roleId) {
        try {
            if (StringUtil.isEmpty(account)) {
                return new Result(true, ResultEnum.EMPTY.getType(), "请输入账号", null);
            }
            if (StringUtil.isEmpty(password)) {
                return new Result(true, ResultEnum.EMPTY.getType(), "请输入密码", null);
            }
            AdminInfo adminInfo = adminInfoService.findOne(id);
            if (adminInfo == null) {
                return new Result(true, ResultEnum.NORECORD.getType(), ResultEnum.NORECORD.getInfo(), null);
            }
            if (!password.equals(adminInfo.getPassword())) {
                password = md5.getMD5ofStr(password);
                adminInfo.setPassword(password);
            }
            adminInfo.setRoleId(roleId);
            adminInfo.setAccount(account);
            AdminInfo param = new AdminInfo();
            param.setId(adminInfo.getId());
            param.setRoleId(adminInfo.getRoleId());
            param.setAccount(adminInfo.getAccount());
            return adminInfoService.updateAdminInfo(param);
        } catch (Exception e) {
            logger.info(ResultEnum.ERROR.getType(), e);
            return new Result(true, ResultEnum.ERROR.getType(), ResultEnum.ERROR.getInfo(), null);
        }
    }

    /**
     * 删除账户
     *
     * @param ids
     * @return
     */
    @RequestMapping(value = "/removeAdmin", method = RequestMethod.POST)
    public Result removeAdmin(@RequestParam(name = "ids", required = true) String ids) {
        try {
            return adminInfoService.removeAdmin(ids);
        } catch (Exception e) {
            logger.info(ResultEnum.ERROR.getType(), e);
            return new Result(true, ResultEnum.ERROR.getType(), ResultEnum.ERROR.getInfo(), null);
        }
    }

    /**
     * 管理员列表页面角色集合
     *
     * @return
     */
    @RequestMapping(value = "/listRoles", method = RequestMethod.POST)
    public Result listRoles() {
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            List<RoleInfo> roleInfoList = new ArrayList<RoleInfo>();
            Assist assist = new Assist();
            roleInfoList = (List<RoleInfo>) roleInfoService.find(assist).getRows();
            return new Result(false, ResultEnum.SUCCESS.getType(), roleInfoList);
        } catch (Exception e) {
            logger.info(ResultEnum.ERROR.getType(), e);
            return new Result(true, ResultEnum.ERROR.getType(), ResultEnum.ERROR.getInfo(), null);
        }
    }
}
